import { Request, RequestHandler, Response } from "express";
import {
  IGetAnnouncementByIdReq,
  IAddAnnouncementReq,
  IUpdateAnnouncementReq,
  IDeleteAnnouncementReq,
} from "../../models/announcement.model";
import * as AnnouncementService from "../services/announcement.service";
import fs from "fs";
import { IncomingForm } from "formidable";
import { convertToLocalDateString } from "../utils/date";

/**
 * Get active announcement records
 *
 * @param req Express Request
 * @param res Express Response
 */
export const getAnnouncements: RequestHandler = async (
  req: Request,
  res: Response
) => {
  try {
    const announcements = await AnnouncementService.getAnnouncements();

    res.status(200).json({
      data: announcements,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[announcements.controller][getAnnouncements][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "通知列表获取失败！",
    });
  }
};

/**
 * Get announcement record based on id provided
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const getAnnouncementById: RequestHandler = async (
  req: IGetAnnouncementByIdReq,
  res: Response
) => {
  try {
    const announcement = await AnnouncementService.getAnnouncementById(req.params.id);

    res.status(200).json({
      data: announcement,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[announcements.controller][getAnnouncementById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "通知信息获取失败！",
    });
  }
};

/**
 * Inserts a new announcement record
 *
 * @param req Express Request
 * @param res Express Response
 */
export const addAnnouncement: RequestHandler = async (
  req: IAddAnnouncementReq,
  res: Response
) => {
  try {
    req.body.createdTime = new Date(Date.now());
    req.body.updatedTime = req.body.createdTime;
    req.body.announcementDate = req.body.announcementDate
      ? convertToLocalDateString(req.body.announcementDate)
      : null;
    const result = await AnnouncementService.insertAnnouncement(req.body);

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[announcements.controller][addAnnouncement][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    if (error.code === "ER_DUP_ENTRY") {
      res.status(500).json({
        message: "通知名称重复，请重新输入！",
      });
    } else {
      res.status(500).json({
        message: "通知保存失败！",
      });
    }
  }
};

/**
 * Updates existing announcement record
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const updateAnnouncementById: RequestHandler = async (
  req: IUpdateAnnouncementReq,
  res: Response
) => {
  try {
    req.body.updatedTime = new Date(Date.now());
    req.body.announcementDate = req.body.announcementDate
      ? req.body.announcementDate.length === 10 ? req.body.announcementDate : convertToLocalDateString(req.body.announcementDate)
      : null;
    const result = await AnnouncementService.updateAnnouncement({
      ...req.body,
      id: req.params.id,
    });

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[announcements.controller][updateAnnouncementById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    if (error.code === "ER_DUP_ENTRY") {
      res.status(500).json({
        message: "通知名称重复，请重新输入！",
      });
    } else {
      res.status(500).json({
        message: "通知更新失败！",
      });
    }
  }
};

/**
 * deletes a announcement
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const deleteAnnouncementById: RequestHandler = async (
  req: IDeleteAnnouncementReq,
  res: Response
) => {
  try {
    const result = await AnnouncementService.deleteAnnouncement(req.params.id);

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[announcements.controller][deleteAnnouncementById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "通知删除失败！",
    });
  }
};

/**
 * upload an docs file for a project
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const upload: RequestHandler = async (req: any, res: Response) => {
  try {
    console.log(req);
    let info = { status: "0", message: "上传文件成功", srcurl: "" };
    // 初始化处理文件对象
    var form = new IncomingForm();
    form.parse(req, function (error, fields, files) {
      if (error) {
        info.status = "1";
        info.message = "上传文件失败！";
        res.send(info);
      }

      const folderPath = "public/project/";
      if (!fs.existsSync(folderPath)) {
        fs.mkdirSync(folderPath);
      }
      const fullName = `${folderPath}${Date.now().toString()}_${
        files.file[0].originalFilename
      }`;
      fs.writeFileSync(`${fullName}`, fs.readFileSync(files.file[0].filepath)); // 存储文件到public静态资源文件夹下
      info.srcurl = fullName;
      res.send(info);
    });
  } catch (error) {
    console.error(
      "[machine.controller][deleteMachineById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "上传文件失败！",
    });
  }
};
